package co.y.t.hyfPay;

import java.security.MessageDigest;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

/**
 * 安全工具类
 * @author zhangyu
 *
 */
public class Safe {
	
	static String[] strDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	/** MD5数据 */
	public static String md5(String txt) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(txt.getBytes("UTF-8"));
			StringBuffer buff = new StringBuffer();
			for (int i = 0; i < bytes.length; i++) {
				int bt = bytes[i];
				if (bt < 0) {
					bt += 256;
				}
				int iD1 = bt / 16;
				int iD2 = bt % 16;
				buff.append(strDigits[iD1]).append(strDigits[iD2]);
			}
			return buff.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 签名数据 */
	public static String sign(TreeMap<String, String> params){
		try {
			Set<Entry<String,String>> entrySet = params.entrySet();
	        StringBuffer buff = new StringBuffer();
			for (Entry<String, String> entry : entrySet) {
				buff.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
			buff.append(Config.key);
			System.out.println("待签名数据：" + buff.toString());
			System.out.println(Config.key);
			System.out.println("md5待签名数据：" + md5(buff.toString()));
			return md5(buff.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/** 签名数据 */
	public static String sign4mini(TreeMap<String, String>  params){
		try {
			Set<Entry<String,String>> entrySet = params.entrySet();
			StringBuffer buff = new StringBuffer();
			for (Entry<String, String> entry : entrySet) {
				buff.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
			buff.append(Config.key);
			System.out.println("小程序待签名数据：" + buff.toString());
			System.out.println(Config.key);
			System.out.println("小程序md5待签名数据：" + md5(buff.toString()));
			return md5(buff.toString());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
